package com.ljq.software_springboot.softwareprogram;

import com.ljq.software_springboot.softwareprogram.entity.ChatMessage;
import com.ljq.software_springboot.softwareprogram.imp.ChatMessageServiceImpl;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class ChatWebSocketHandler extends TextWebSocketHandler {

    // 用于保存用户的 WebSocket 会话
    private static final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    @Autowired
    private ChatMessageServiceImpl messageService;

    @Override
    public void handleTextMessage(WebSocketSession session, org.springframework.web.socket.TextMessage message) throws Exception {
        String messageStr = message.getPayload();
        System.out.println("Received message: " + messageStr);

        // 使用 FastJSON 解析消息
        ChatMessage msg = JSON.parseObject(messageStr, ChatMessage.class);

        // 保存消息到数据库
        messageService.saveMessage(msg);

        // 根据 recipientId 获取对应的会话
        WebSocketSession recipientSession = sessions.get(msg.getRecipientId());
        if (recipientSession != null && recipientSession.isOpen()) {
            // 推送消息给目标会话
            recipientSession.sendMessage(new org.springframework.web.socket.TextMessage(messageStr));
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 获取用户的 ID 并将其与会话关联
        String userId = (String) session.getAttributes().get("userId");
        if (userId != null) {
            sessions.put(userId, session);
            System.out.println("User " + userId + " connected");
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
        // 获取用户的 ID 并移除会话
        String userId = (String) session.getAttributes().get("userId");
        if (userId != null) {
            sessions.remove(userId);
            System.out.println("User " + userId + " disconnected");
        }
    }
}
